<template>
  <div>
    <dl class="m-categroy">
      <dt>按拼音首字母选择：</dt>
      <dd v-for="item in list" :key="item">
        <a :href="'#city-' + item">{{ item }}</a>
      </dd>
    </dl>
    <dl v-for="item in citiesCate" :key="item.title" class="m-categroy-section">
      <dt :id="'city-' + item.title">
        {{ item.title }}
      </dt>
      <dd>
        <span v-for="c in item.city" :key="c.city" @click="select(c)"> {{ c.city }} </span>
      </dd>
    </dl>
  </div>
</template>

<script>
import pyjs from 'js-pinyin'
import { mapActions } from 'vuex'
import cookies from 'vue-cookies'
export default {
  data () {
    return {
      list: 'ABCDEFGHJKLMNPQRSTWXYZ'.split(''),
      citiesCate: []
    }
  },
  mounted () {
    this.getCities()
  },
  methods: {
    ...mapActions('geo', ['setPosition']),
    async getCities () {
      // eslint-disable-next-line prefer-const
      let citiesCate = []
      const { status, data: { city } } = await this.$axios.get('/geo/getCity')
      if (status === 200) {
        let p
        let c
        const d = {}
        // 遍历返回的城市数组
        city.forEach((item) => {
          // 获取所有城市的首字母
          p = pyjs.getFullChars(item.name).toLocaleLowerCase().slice(0, 1)
          // 获取这些首字母的编码
          c = p.charCodeAt(0)
          // 判断这些编码是否在有效范围内
          if (c > 96 && c < 123) {
            // 判断d[p]中是否有值
            if (!d[p]) {
              // 给每个对应的字母添加一个空数组
              d[p] = []
            }
            // 把对应城市存储到对应的字母当中
            d[p].push({
              province: item.province,
              city: item.name
            })
          }
        })
        // 把这个对象转化为数组
        // eslint-disable-next-line prefer-const
        for (let [k, v] of Object.entries(d)) {
          citiesCate.push({
            title: k.toUpperCase(),
            city: v
          })
          citiesCate.sort((a, b) => a.title.charCodeAt(0) - b.title.charCodeAt(0))
          this.citiesCate = citiesCate
        }
      }
    },
    // 选择切换城市
    select (i) {
      const city = i.city === '市辖区' ? i.province : i.city
      // 清除cookies
      cookies.remove('city')
      // 获取local中的访问记录
      const historyCollects = JSON.parse(window.localStorage.getItem('historyCollects')) || []
      // 判断该数据中是否已经有该城市
      const index = historyCollects.findIndex(item => item.city === city)
      if (index !== -1) {
        // 证明有该城市,删除该条数据
        historyCollects.splice(index, 1)
      }
      // 把该条数据追加到最前面
      historyCollects.unshift({ province: i.province, city })
      // 修改vuex中的城市定位
      this.setPosition({
        province: i.province,
        city
      })
      // 把该城市存回cookies
      cookies.set('city', city)
      // 把数据存回local
      window.localStorage.setItem('historyCollects', JSON.stringify(historyCollects))
      // 返回首页
      location.href = '/'
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/css/changeCity/categroy.scss';
</style>
